package com.csot.ipscan;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;

import com.alibaba.fastjson2.JSON;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;

@Path(value = "/")
public class IndexController extends Controller {

    Log log = Log.getLog(IndexController.class);

    public static volatile Semaphore SEMAPHORE = new Semaphore(1);

    @Inject
    IpScanService iss;

    public void index() {

    }

    public void start() {

        Ret ret = JSON.parseObject(getRawData(), Ret.class);

        if (!SEMAPHORE.tryAcquire()) {
            Ret kv = Ret.create();
            kv.set("code", 300);
            kv.set("msg", "任务在执行");
            kv.set("job_id", SysData.job_id);
            renderJson(kv);
            return;
        }

        try {
            Ret kv = Ret.create();
            kv.set("code", "200");
            kv.set("msg", "创建探活任务成功");
            SysData.job_id = ret.getStr("job_id");
            SysData.over = "start";
            renderJson(kv);
            log.info("创建探活任务成功：" + ret.getStr("job_id"));
            CompletableFuture.runAsync(() -> {
                // TODO Auto-generated method stub
                try {
                    iss.handle(ret);
                } catch (InterruptedException | ExecutionException e) {
                    // TODO Auto-generated catch block
                    log.error("", e);
                }
            });
        } catch (Exception e) {
            log.error("", e);
        } finally {
            SEMAPHORE.release();
        }
    }

    public void stop() {

        SEMAPHORE.release();
        SysData.over = "stop";
        Ret kv = Ret.create();
        kv.set("code", "200");
        kv.set("msg", "已通知任务停止");
        renderJson(kv);

    }

    public void list() {
        String type = this.getPara("type", "ip");
        Ret ret = Ret.create();
        if ("ip".equals(type))
            ret.set("data", SysData.iplist);
        else
            ret.set("data", SysData.list);
        ret.set("job_id", SysData.job_id);
        if (SEMAPHORE.tryAcquire()) {
            ret.set("code", 200);
            SEMAPHORE.release();
        } else {
            ret.set("code", 300);
        }
        renderJson(ret);
    }

}
